Skip to content

perf(update): contiguous-patch allocation fix + prepared-statement batch API (prepared 4,69× raw) - #534

Merged
MPCoreDeveloper merged 18 commits into
masterfrom
perf/002-sqlite-update-delete-parity
Nov 30, 2026
Merged

MPCoreDeveloper merged 18 commits into
masterfrom
perf/002-sqlite-update-delete-parity

Conversation

@MPCoreDeveloper

@MPCoreDeveloper MPCoreDeveloper commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

Summary

Two landed, tested engine changes on the fair-PK UPDATE arm, plus the spec-kit investigation that produced them.

1. Contiguous-patch allocation fix (UPDATE 0,73× → ~0,83×, −21 % alloc)

TryBulkUpdateContiguousFixedWidth allocated a fresh byte[FixedSize] per row and TryOverwriteFixedWidthInPlace a second copy. A span-in-place TryOverwriteFixedWidthInPlaceSpan patches the caller's per-row buffer (the buffer is required — the storage layer buffers the array reference); the gate's O(columns) scan → the shared GetColumnIndexCache. Quiet-machine A/B: UPDATE gap vs SQLite 1,4× → 1,2× median; canaries 53/53.

2. Prepared-statement batch API (prepared 4,69× raw)

IDatabase.ExecuteBatchPrepared(template, parameterSets): classifies a canonical UPDATE template once and binds parameters per row into UpdateMultiplePrepared — no per-statement scan, no ParseValue, no string materialisation. New --pk-prepared arm:

arm time ops/sec
RAW ExecuteBatchSQL 117,4 ms 85.201
PREPARED ExecuteBatchPrepared 25,0 ms 399.672
prepared / raw — 4,69×

Verify: id=500 reads 49.950 (= 500 × 99,9), matching raw. Single-file keeps the raw path (NotSupportedException).

Investigation (specs)

  • specs/002-… — plan + full --pk-profile evidence; Phase 9: deferred-span refuted (allocation ~12 %, SingleItemUpdate negligible); Phase 10: commit/write-volume investigated (field-level write ~75× less write = durability redesign, owner-gated).
  • specs/003-… — internal shape-cache refuted (can't skip the scan; exact cache misses distinct literals); real path = this prepared-statement API, implemented.

Verification

ExecuteBatchPreparedTests (2) + fixed-width/reopen canaries 53/53, wider suite 3087 / 0 failed / 22 skipped, build 0 errors. Separate from the metadata-flush fix (PR #533).

Add specs/002-sqlite-update-delete-parity (spec.md, plan.md, tasks.md): the
careful plan to close the fair-PK UPDATE (0.73x) and DELETE (0.82x) gap vs
SQLite without regressing INSERT (1.35x ahead) or READ (1.29x ahead), using
.NET 11 / C# 15 (a deferred-span ref struct + single-assignment classification).

Includes:
- the same-session --pk-profile evidence: parse/classification is 35.0% of the
  UPDATE pass at 497 B/call -- the largest attributable per-statement stage;
- the execution-ready design (IReadOnlyDictionary widening + SingleItemUpdate),
  verified safe because the core helpers read `updates` without mutating it;
- the honest predicted outcome: allocation -27% on parse but timing low-single-
  digit / likely inside this box noise, so "not shipped" per the NET11 timing
  rail until a quiet-machine A/B proves a win.

No engine source change here -- the implementation is sequenced as a dedicated
quiet-machine session per NET11_C15_PERFORMANCE_PLAN.md P2 (default-off + full
matrix + measured timing win). Baseline canaries verified green this session
(27/27 fixed-width + reopen).
…ealed (#534)

The Dictionary->IReadOnlyDictionary widening was attempted and reverted (tree clean, build green). It is mechanical but cascades through more helpers than first listed (TryResolveRuntimeOffsets, AllUpdatedColumnsFit, ValidateBatchKeyChanges[Core], UpdateTouchesKeyColumns, TryGetUpdateValue), is blocked on the adapter INPUT signatures (value-tuple invariance) and the public ITable surface. Pins the exact edit list for the dedicated session; no engine source change.
The full --pk-profile showed the row-locate stage (30,7%) allocated ~one
record per row for nothing: the contiguous fixed-width UPDATE loop made a fresh
new byte[FixedSize] per row AND TryOverwriteFixedWidthInPlace made a second
copy. The per-row buffer is required (the storage layer buffers the array
reference, and plaintext EncryptRecord returns the same instance -- a shared
scratch corrupts every row, caught by 3 canaries), but the second copy is not.

- Add a span-in-place TryOverwriteFixedWidthInPlaceSpan that patches the
  caller's per-row buffer instead of allocating a copy; the contiguous path
  passes one fresh per-row buffer to the engine.
- Replace the gate's O(columns) linear column scan per statement with the
  shared O(1) GetColumnIndexCache().

The whole-file snapshot is a dead end for this arm: TryLoadWholeFileForUpdatePatch
returns null immediately for fixed-width records (row-snapshot 0,2%).

Measured: row-locate allocation 6,41 -> 5,05 MB/batch (-21%); --pk FW plaintext
UPDATE 0,73x -> 0,83-0,89x across clean runs (548.970 -> 632.755 ops/s cleanest;
SQLite reference noisy, needs a quiet-machine A/B). INSERT/READ not regressed.
Correctness: canaries 53/53, wider suite 3085/0/22. Refs #534.
@MPCoreDeveloper MPCoreDeveloper changed the title docs(perf): spec-kit plan to close the SQLite UPDATE/DELETE gap (plan only) perf(update): cut the contiguous fixed-width UPDATE patch allocation (UPDATE 0,73×→0,83–0,89×) Nov 29, 2026
…SingleItemUpdate negligible); real lever is a prepared DML shape cache
…e-volume investigation (field-level write = owner-gated)
…ement scan; exact cache misses distinct literals); real path is a prepared-statement API
…w UPDATE)

Add IDatabase.ExecuteBatchPrepared(template, parameterSets): a canonical UPDATE
template is classified ONCE and each row binds its parameters into the shared
UpdateMultiplePrepared core -- no per-statement scan, no ParseValue, no
per-statement string materialisation. This is the prepared path the raw-SQL
batch cannot take (the shape-cache alternative was refuted: the template key
needs the same scan, and an exact-SQL cache misses distinct literals).

Single-file storage keeps the raw path (NotSupportedException, documented).

Measured (--pk-prepared, AppendOnly fixed-width plaintext, 100.000 rows /
10.000 updates, same data, same run):
  RAW ExecuteBatchSQL        117,4 ms / 85.201 ops/s
  PREPARED ExecuteBatchPrepared  25,0 ms / 399.672 ops/s
  prepared / raw             4,69x faster

Verify: id=500 reads 49.950 (= 500 x 99,9), matching raw. Correctness pinned by
ExecuteBatchPreparedTests (2 cases); wider suite 3087 / 0 / 22.

Scope: prepared workload, not the raw-SQL arm the SQLite comparison uses; the
raw UPDATE gap (~0,83x, contiguous-patch win) is unchanged.
@MPCoreDeveloper MPCoreDeveloper changed the title perf(update): cut the contiguous fixed-width UPDATE patch allocation (UPDATE 0,73×→0,83–0,89×) perf(update): contiguous-patch allocation fix + prepared-statement batch API (prepared 4,69× raw) Nov 29, 2026
…n 5.4)

- ExecuteBatchPrepared accepts the canonical DELETE template: the template is
  classified once and each parameter set binds its typed key into
  DeleteBatchStructured (the same PK / hash-index / contiguous resolvers the SQL
  batch DELETE path runs). Red->green: 2 failures before, 0 after; the UPDATE
  and rejection rails stay green.
- specs/004: the corrected READ/INSERT/UPDATE/DELETE findings -- the point-lookup
  parse is already skipped (SimpleSelectPlan) and ExecuteQueryStruct already
  exists; INSERT is ahead on plaintext and behind only by the deliberate
  encryption tax; the raw UPDATE levers are exhausted.
- specs/005: the commit-flush page-read candidate was built and measured and is
  REJECTED (commit 10.6 -> 32.0 ms: 2 coalesced cache-warm reads cost less than
  284 coverage passes + 284 per-page writes). Reverted in the same session.
- 5.4 providers re-validation: 451 tests / 0 failed across EF Core, Dapper,
  Linq2DB, Functional, Functional.EFCore and Provider.Sync.
- Benchmark, --pk on the clean build, same-run SQLite: FW plaintext INSERT 1.25x
  and READ 1.43x ahead, UPDATE 0.91x, DELETE 0.77x; --pk-default INSERT 1.22x
  and READ 1.10x ahead; --multirowinsert 3.143 B/row, data 2.320.000 B, arena 0.
- --gate PASSED on the documented re-run (first run 1.56x default UPDATE on a
  NOISY box; quiet check + -Apply, re-run 1.16x ok, 8/8 capability ok).
- Regime: net11.0 GA SDK 11.0.100, Release/JIT, SHARPCOREDB_BENCH_TEMP=D:\scdb-bench-tmp.
…ch (plan 006)

- US1: TryReadContiguousFixedWidthRecords decrypts the contiguous span on
  Parallel.For above 64 records (latched failure, whole-batch rejection kept).
- US2: TryBulkUpdateContiguousFixedWidth seals the patched payloads the same way
  for encrypted files; BufferOrWriteOverwriteInPlace resolves its base-length cache
  inside appendLock (it was outside - a latent race once the batch calls it from
  parallel workers).
- Safe because AesGcmEncryption keeps one cipher per thread and derives every
  nonce from an Interlocked counter; no format, encryption-strength or durability
  change.
- Diagnostics: BulkContiguousParallelDecryptBatches / ...EncryptBatches, both
  proven red (Expected 1, Actual 0) by disabling each guard; 2 tests.
- Measured, same-session PRE/POST A/B, --pk, at-rest tax within the run:
  UPDATE 1.945x -> 1.585x (-19%), DELETE directionally better; US1 alone was
  neutral on UPDATE (the seal dominates) and better on DELETE 2/2.
- Verification: build 0; focused 38/38; wider suite 2987/0/6; canaries 59/0;
  --gate PASSED on the documented re-run (run 1 1.61x default UPDATE on a NOISY
  box, re-run 1.10x ok, 8/8 capability ok).
- Specs: 006 (this), 007 AOT cleanup, 008 single-file metadata parity, 009 the
  four owner decisions with evidence.
- Regime: net11.0 GA SDK 11.0.100, Release/JIT, SHARPCOREDB_BENCH_TEMP=D:\scdb-bench-tmp.
… cleanup (plans 007/008)

- 008: SingleFileDatabase declares IMetadataProvider (implicit, the shape Database
  uses). It already answered GetTables/GetColumns via IDatabase, but the probe
  db is IMetadataProvider was false for a .scdb file and true for a directory
  database. SingleFileMetadataParityTests asserts the probe and column-for-column
  metadata equality across both modes; red before the declaration.
- 007: verified DONE - the roadmap item was stale. The B-tree factory is already
  a closed-generic switch (no Activator/GetMethod) and AotJsonSerializer resolves
  GetTypeInfo<T>() with source-generated contexts under AOT. Measured: the AOT
  publish of the engine + smoke tool is 0 errors / 0 IL-AOT warnings and the
  native exe passes (exit 0, IsReflectionEnabledByDefault=False), including
  at-rest encryption and key rotation. No code change for 007.
- Verification: build 0; focused 18/18; wider suite 2988/0/6; canaries 60/0;
  --gate PASSED.
- Regime: net11.0 GA SDK 11.0.100, Release/JIT, SHARPCOREDB_BENCH_TEMP=D:\scdb-bench-tmp.
…r COLLATE (decisions D1/D2/D3)

- D1=A: every key column is parsed and persisted (ColumnFlags.PrimaryKey on each)
  plus a free marker bit (KeyModelledFlag, bit 6); SingleFileTable enforces the
  key tuple's uniqueness on INSERT, multi-row INSERT and all three UPDATE paths.
  Files written before the marker stay unenforced, and PrimaryKeyIndex (the
  storage key) is still the last key column. The four skipped
  PrimaryKeyUniquenessTests single-file cases now run and pass.
- D2=A: COLLATE NOCASE/RTRIM is parsed, persisted in flag bits 8-11, reloaded on
  reopen and honoured by the WHERE evaluator (ordinal fast path bypassed for such
  a column) and ORDER BY. The skipped single-file ORDER BY collation test now runs
  and passes; SingleFileCollationTests adds WHERE/reopen coverage.
- D3=B: Int32 stays the default, but the batch literal path no longer stores an
  out-of-range INTEGER as 0 (it throws the same actionable message as the
  single-statement path), and the single-file DDL now honours
  UseSqliteIntegerAffinity instead of hardcoding it off.
- D4=C: BLOCKED - .NET 11 ships no inbox Zstandard (System.IO.Compression 11.0.0
  has ZLib only), so Zstd needs a third-party package = the owner package rail.
  Recorded in specs/009 with the two ways forward.
- Verification: build 0; focused 86/86; wider suite 2994/0/1; canaries 75/0;
  --gate PASSED.
- Regime: net11.0 GA SDK 11.0.100, Release/JIT, SHARPCOREDB_BENCH_TEMP=D:\scdb-bench-tmp.
… the Zstd record (D4)

- Bug found by the wider suite (21 failures): SingleFileDatabaseBatchExtension
  keeps a STATIC prepared-INSERT cache keyed by the table NAME only, so two
  databases whose tables share a name but not a shape mapped each other's rows
  through the wrong column list - a valid INSERT INTO docs (name, age) failed
  with "Column 'name' cannot be NULL" once another database's docs shape filled
  the cache. The key now carries the column signature (name + columns + types)
  and the cache is bounded at 256 shapes. SingleFileBatchSchemaIsolationTests
  reproduces it (red with the name-only key).
- D4 correction: .NET 11 DOES ship in-box Zstandard (System.IO.Compression.*
  Zstandard*) - the earlier scan searched ZStandard instead of Zstandard - and
  the engine already implements it (BlockCompressor.Zstd, header-recorded mode,
  ValidateHeader enforcement). Fixed the two stale claims (Zstd "will throw";
  BlockFlags.Compressed "reserved, always 0") and added the missing end-to-end
  test: Zstd write -> 200-row round-trip after reopen -> update -> wrong-mode open
  throws the actionable message; plus an encrypted variant.
- Verification: wider suite 2997/0/1 (exit 0); canaries 116/0; --gate PASSED.
- Regime: net11.0 GA SDK 11.0.100, Release/JIT, SHARPCOREDB_BENCH_TEMP=D:\scdb-bench-tmp.
…coverage 49.00%, Sonar triage

Tests first (owner priority order).

- new suites: SimdHelperTests (every public SIMD primitive on a short and a long span, plus the
  deserializers'' wire layouts), PageBasedAdapterTests (insert/read/update/delete/batch/metrics/
  transactions/reopen - the adapter was at 0%), CorruptionDetectorTests (all four validation modes,
  0% before), SingleFileKeyMoveTests (D1=A on every UPDATE/DELETE path).

Defects found by those tests, fixed here with red->green proof (9 of 24 SingleFile tests failed with
only the src change reverted; the adapter insert failed with "Page full"):

- SingleFileStorageProvider: a block read did not drain the write-behind queue, so it saw the zero
  fill of an unwritten region and the checksum self-heal rewrote the registry to match - the block
  was lost. ReadBlockAsync now flushes pending writes; the pending flag clears only when the queue
  is empty (a write enqueued during a flush escaped HasPendingChanges - a durability gap).
- PageBasedAdapter.Dispose never flushed the shared provider, so a reopen lost every page.
- SingleFileTable: a rejected UPDATE left the row altered on all four paths - one shared
  ApplyMatchedUpdates validates the prospective key set before the first write; UpdateByPrimaryKey
  gained the check it never had; DELETE FROM t releases the key set.
- COLLATE RTRIM was parsed but compared ordinally, and key uniqueness compared ordinal text
  (NOCASE key accepted ''aa'' and ''AA''): CompareText + CanonicalKeyPart per collation.
- SimdHelper.HorizontalSum summed half of each 128-bit lane (5 elements gave 8, not 15).
- SimdHelper.DeserializeBatchDouble ignored its null flags.

Quality state:

- coverage 47.89% -> 49.00% of 62,791 lines (engine 55.32% -> 56.92%), measure-coverage PASS at the
  18% floor; wider suite 3060 / 0 failed / 1 skipped (run twice, the second after the Sonar refactors)
- mutation: engine-sqlfunctions re-run with the documented filter - 33 killed / 22 survived /
  70 no-coverage over 125 mutants, 26.40%, 4m14s (2026-11-13: 27.73%)
- SonarCloud: 24 real S3358 sites fixed across 10 files; the 307 open findings are triaged by rule
  in docs/quality/SONAR_AND_COVERAGE.md (S3776/S127/S3267 accepted by design, S1192 is the SQL
  standard vocabulary, stale line numbers explained)
- docs: CHANGELOG, known issues (#4 fixed at the provider layer, #10/#11 closed), PROJECT_STATUS,
  tiered coverage floors, WORKLOG session 90
Quality patch on the net11.0 / C# 15 line.

- versions: 28 packable src projects 2.2.0 -> 2.2.1, Directory.Packages.props
  SharpCoreDBVersion, FileVersion 2.2.1.0 (AssemblyVersion stays 2.2.0.0, the 2.1.4
  convention for a patch); the two missing central PackageVersion entries
  (SharpCoreDB.Search, SharpCoreDB.HybridSearch) added so the list matches the
  packable set.
- README: current release / previous release, the two-line table, a new
  "What is new in v2.2.1" section, and all 30 install commands at 2.2.1.
- docs: CHANGELOG [Unreleased] -> [2.2.1] - 2026-11-30 with a fresh stub,
  PROJECT_STATUS (version/status/current-release narrative/history), INDEX,
  docs/README, manual/performance, and the package guides install snippets.
  Historical 2.2.0 references stay.
- WORKLOG session 90 addendum 2: the bump, the docs sweep, the merge.

Validated: SharpCoreDB.CI.slnf 0 errors; DocumentationConsistencyTests +
SingleFileKeyMoveTests + SingleFileCollationTests + PageBasedAdapterTests 45/0.
@MPCoreDeveloper
MPCoreDeveloper merged commit dea9aa1 into master Nov 30, 2026
9 of 10 checks passed
@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant